package private

import (
	"dc-go/global"
	"dc-go/model"
	"errors"
)

type ServiceOrg struct{}

func (s *ServiceOrg) GetOrgList(requestOrgList model.RequestGetOrgList) (role interface{}, total int64, err error) {
	if requestOrgList.SortBy == "" {
		requestOrgList.SortBy = "id"
		requestOrgList.Desc = false
	}
	pageSize := requestOrgList.PageSize
	offset := requestOrgList.PageSize * (requestOrgList.Page - 1)
	db := global.DcDb.Model(&model.SysOrg{})
	var orgList []model.SysOrg
	//配置搜索
	if requestOrgList.OrgCode != "" {
		db = db.Where("org_code like ?", "%"+requestOrgList.OrgCode+"%")
	}
	if requestOrgList.OrgName != "" {
		db = db.Where("org_name like ?", "%"+requestOrgList.OrgName+"%")
	}
	if requestOrgList.OrgLevel != "" {
		db = db.Where("org_level= ?", requestOrgList.OrgLevel)
	}
	if requestOrgList.MktAreaName != "" {
		db = db.Where("mkt_area_name= ?", requestOrgList.MktAreaName)
	}
	if requestOrgList.DeptName != "" {
		db = db.Where("dept_name= ?", requestOrgList.DeptName)
	}
	if requestOrgList.GroupName != "" {
		db = db.Where("group_name= ?", requestOrgList.GroupName)
	}
	if requestOrgList.DutyZoneName != "" {
		db = db.Where("duty_zone_name= ?", requestOrgList.DutyZoneName)
	}
	if requestOrgList.RegionName != "" {
		db = db.Where("region_name= ?", requestOrgList.RegionName)
	}
	err = db.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}
	err = db.Limit(pageSize).Offset(offset).Order(model.OrderByColumn(requestOrgList.SortBy, requestOrgList.Desc)).Find(&orgList).Error
	return orgList, total, err
}

func (s *ServiceOrg) QueryOrgById(id uint) (OrgInfo model.SysOrg, err error) {
	var org model.SysOrg
	err = global.DcDb.First(&org, "id = ?", id).Error
	return org, err
}

func (s *ServiceOrg) QueryRoleByOrg(orgCode *model.RequestOrgCode) (role []model.SysRole, err error) {
	org := model.SysOrg{
		OrgCode: orgCode.OrgCode,
	}
	var roleList []model.SysRole
	err = global.DcDb.Model(&org).Association("Role").Find(&roleList)
	return roleList, err
}

func (s *ServiceOrg) RemoveOrgRole(toDeleteOrgRole *model.RequestOrgRole) (err error) {
	var orgRole model.SysOrgRole
	err = global.DcDb.Where("org_code = ? and role_code = ?", toDeleteOrgRole.OrgCode, toDeleteOrgRole.RoleCode).Delete(&orgRole).Error
	return err
}

func (s *ServiceOrg) AddOrgRole(toAddOrgRole *model.RequestOrgRoleAdd) (err error) {
	var orgRole []model.RequestOrgRole
	for _, r := range toAddOrgRole.RoleCode {
		oR := model.RequestOrgRole{
			RoleCode: r,
			OrgCode:  toAddOrgRole.OrgCode,
		}
		orgRole = append(orgRole, oR)
	}
	if len(orgRole) != 0 {
		err = global.DcDb.Model(&model.SysOrgRole{}).Save(&orgRole).Error
		return err
	} else {
		return errors.New("本次操作没有影响! ")
	}
}
